package com.study.mybatis.dao.impl;

import com.study.mybatis.dao.StudentDao;
import com.study.mybatis.entity.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * @author wei.zhao
 * @date 2021年11月25日 14:21
 */
public class StudentDaoImpl implements StudentDao {

    //注入SqlSessionFactory
    public StudentDaoImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    private SqlSessionFactory sqlSessionFactory;

    @Override
    public Student findStudentById(Long id) {
        SqlSession session = sqlSessionFactory.openSession();
        Student student = null;
        try {
            //通过sqlsession调用selectOne方法获取一条结果集
            // 参数1：指定定义的statement的id,参数2：指定向statement中传递的参数
            student = session.selectOne("test.findStudentById", id);
            System.out.println(student);
        } finally {
            session.close();
        }
        return student;
    }

    @Override
    public List<Student> findStudentsByName(String name) {
        SqlSession session = sqlSessionFactory.openSession();
        List<Student> students = null;
        try {
            students = session.selectList("test.findStudentsByName", name);
            System.out.println(students);
        } finally {
            session.close();
        }
        return students;
    }

    @Override
    public void insertStudent(Student student) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            session.insert("test.insertStudent", student);
            //必须提交，默认手动提交
            session.commit();
        } finally {
            session.close();
        }
    }

}
